package com.example.xianji.activity;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.adapter.Collection_Adapter;
import com.example.xianji.BGARefresh.BGARefreshLayout;
import com.example.xianji.BGARefresh.BGARefreshLayout.BGARefreshLayoutDelegate;
import com.example.xianji.bean.Collection;

import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Main_My_CollectionActivity extends Activity implements
        BGARefreshLayoutDelegate {
    public static Boolean bianji_flag = false;
    /***************** 我收藏的产品,需求,技术,服务页面 *******************************************/
    private BGARefreshLayout collection_RefreshLayout;
    //    private SharedPreferences sp;
//    private Editor ed;
    private ArrayList<Collection> collection_list = new ArrayList<Collection>();
    private Collection_Adapter mCollection_Adapter;
    private ListView collection_my_listview;
    private int page = 1;
    private RelativeLayout my_collection_back;
    private TextView collection_bianji, text_collection_title;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    collection_my_listview.setAdapter(mCollection_Adapter);
                    collection_RefreshLayout.endRefreshing();
                    break;
                case 2:
                    mCollection_Adapter.notifyDataSetChanged();
                    collection_RefreshLayout.endLoadingMore();
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__my__collection);
        // XJApplication.getInstance().addActivity(this);
        collection_RefreshLayout = (BGARefreshLayout) findViewById(R.id.collection_RefreshLayout);
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        collection_my_listview = (ListView) findViewById(R.id.collection_my_listview);
        my_collection_back = (RelativeLayout) findViewById(R.id.my_relative_collection_back);
        collection_bianji = (TextView) findViewById(R.id.collection_bianji);
        text_collection_title = (TextView) findViewById(R.id.text_collection_title);
        mCollection_Adapter = new Collection_Adapter(this, collection_list);
        if (getIntent().getStringExtra("collection_type").equals("product")) {
            text_collection_title.setText("我收藏的产品");
        } else if (getIntent().getStringExtra("collection_type").equals(
                "demand")) {
            // 需求
            text_collection_title.setText("我收藏的需求");
        } else if (getIntent().getStringExtra("collection_type").equals(
                "achieve")) {
            // 技术
            text_collection_title.setText("我收藏的技术");
        } else if (getIntent().getStringExtra("collection_type").equals(
                "detail")) {
            // 服务
            text_collection_title.setText("我收藏的服务");
        }
        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                get_collection_data();
            }
        });

        collection_RefreshLayout.setDelegate(this);

        my_collection_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Main_My_CollectionActivity.this.finish();
            }
        });
        collection_bianji.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (bianji_flag) {

                    bianji_flag = false;
                } else {

                    bianji_flag = true;
                }
                mCollection_Adapter.notifyDataSetChanged();
            }
        });

        processLogic(savedInstanceState);

        collection_my_listview
                .setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        if (getIntent().getStringExtra("collection_type")
                                .equals("product")) {
                            // 跳转到产品详细页面
                            Intent intent = new Intent(
                                    Main_My_CollectionActivity.this,
                                    Main_Choose_DaTingActivity.class);
                            intent.putExtra("product_id",
                                    collection_list.get(position).getFid() + "");
                            Main_My_CollectionActivity.this
                                    .startActivity(intent);
                        } else if (getIntent()
                                .getStringExtra("collection_type").equals(
                                        "demand")) {
                            // 需求
                            // 跳转到需求详情页
                            Intent intent = new Intent(
                                    Main_My_CollectionActivity.this,
                                    Main_XuQiu_DetailsActivity.class);
                            intent.putExtra("xuqiu_id",
                                    collection_list.get(position).getId() + "");
                            Main_My_CollectionActivity.this
                                    .startActivity(intent);
                        } else if (getIntent()
                                .getStringExtra("collection_type").equals(
                                        "achieve")) {
                            // 技术
                            Intent intent = new Intent(
                                    Main_My_CollectionActivity.this,
                                    Main_Skill_DetailsActivity.class);
                            intent.putExtra("skill_id",
                                    collection_list.get(position).getFid() + "");
                            Main_My_CollectionActivity.this
                                    .startActivity(intent);
                        } else if (getIntent()
                                .getStringExtra("collection_type").equals(
                                        "detail")) {
                            // 服务
                            Intent intent = new Intent(
                                    Main_My_CollectionActivity.this,
                                    Main_FuWu_DetailsActivity.class);
                            intent.putExtra("fuwu_details_id", collection_list
                                    .get(position).getId());
                            Main_My_CollectionActivity.this
                                    .startActivity(intent);
                        }
                    }
                });
    }

    protected void processLogic(Bundle savedInstanceState) {
        collection_RefreshLayout
                .setRefreshViewHolder(new com.example.xianji.BGARefresh.BGANormalRefreshViewHolder(
                        this, true));
    }

    public void get_collection_data() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();

        parms.addBodyParameter("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        parms.addBodyParameter("page", 1 + "");
        parms.addBodyParameter("type", getIntent().getStringExtra("collection_type"));

        httpUtils.send(HttpMethod.POST, Contant.my_collection, parms,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        try {
                            JSONObject response = new JSONObject(arg0.result);
                            if (response.getInt("status") == 1) {
                                collection_list.clear();
                                JSONArray array = response.getJSONArray("data");
                                if (array.length() == 0) {
                                    Toast.makeText(
                                            Main_My_CollectionActivity.this,
                                            response.getString("msg"), Toast.LENGTH_SHORT)
                                            .show();
                                    collection_bianji.setVisibility(View.GONE);

                                } else {
                                    collection_bianji
                                            .setVisibility(View.VISIBLE);
                                    for (int i = 0; i < array.length(); i++) {
                                        JSONObject obj = array.getJSONObject(i);

                                        Collection mCollection = new Collection();

                                        mCollection.setTitle(obj
                                                .getString("title"));
                                        mCollection.setCreated_at(obj
                                                .getString("created_at"));
                                        mCollection.setFid(obj.getInt("fid"));
                                        mCollection.setType(obj
                                                .getString("type"));
                                        mCollection.setId(obj.getInt("id"));
                                        collection_list.add(mCollection);
                                    }

                                }
                            }
                            handler.sendEmptyMessage(1);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

    }

    public void get_collection_data_more() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        parms.addBodyParameter("page", page + "");
        parms.addBodyParameter("type", getIntent().getStringExtra("collection_type"));

        httpUtils.send(HttpMethod.POST, Contant.my_collection, parms,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        collection_RefreshLayout.endRefreshing();
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        try {
                            JSONObject response = new JSONObject(arg0.result);
                            if (response.getInt("status") == 1) {
                                JSONArray array = response.getJSONArray("data");
                                if (array.length() == 0) {
                                    Toast.makeText(
                                            Main_My_CollectionActivity.this,
                                            "没有更多数据", Toast.LENGTH_SHORT).show();
                                } else {
                                    for (int i = 0; i < array.length(); i++) {
                                        JSONObject obj = array.getJSONObject(i);

                                        Collection mCollection = new Collection();

                                        mCollection.setTitle(obj
                                                .getString("title"));
                                        mCollection.setCreated_at(obj
                                                .getString("created_at"));
                                        mCollection.setFid(obj.getInt("fid"));
                                        mCollection.setType(obj
                                                .getString("type"));
                                        mCollection.setId(obj.getInt("id"));

                                        collection_list.add(mCollection);
                                    }

                                }
                            }

                            handler.sendEmptyMessage(2);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });


    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        page = 1;
        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                get_collection_data();
            }
        });

    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(
            BGARefreshLayout refreshLayout) {
        page++;
        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                get_collection_data_more();
            }
        });

        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
